from os import read
from pandas import read_excel, DataFrame, to_timedelta, concat
from datetime import datetime as dt

from .cnamount import amount_converter

class factory:
    '''
    代表合作钢厂
    '''
    # tidy_data : DataFrame = None
    # oto_loc : dict = None
    # mtm_loc : dict = None
    @property
    def tidy_data(self)->None:
        '''
        干净的出入库台账数据
        '''
        pass   

    def get_oto_loc(self,receipt:str)->dict:
        '''
        获取一对一映射表
        '''
        pass

    @property
    def mtm_loc(self):
        '''
        一对多映射表
        '''
        pass

    def read_data(self, datafile:str, idx)->None:
        '''
        从 excel 文件中读入 raw 数据，并进行规整和清洗，最后形成 tidy_data
        '''
        pass

class huaxing(factory):
    '''
    代表 大冶华鑫实业有限公司
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc_in = {
            "B2": '供货方',
            "F2": '日期',
            None: '车牌号',
        }
        self._oto_loc_out = {
            "B2": '收货方',
            "F2": '日期',
            None: '货物名称',
        }
        self._mtm_loc = {
            '4:11': '行范围',
            'A': '货物名称',
            'C': '车牌号',
            'D': '单位',
            'E': '数量'
        }

    @property
    def tidy_data(self):
        return self._tidy_data

    def get_oto_loc(self, receipt)->dict:
        if(receipt=='入仓单'):
            return self._oto_loc_in
        if(receipt=='出仓单'):
            return self._oto_loc_out
        return None

    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:

        df1 = read_excel(
            datafile, 
            sheet_name=idx, 
            skiprows=2,
            usecols="B:M", 
            names=['日期','车牌号','供货方','货物名称','毛重','皮重','扣重','净重','数量','扣款','销售单价','销售金额'])
        # df2 = read_excel(datafile, 2, skiprows=2, usecols='K:L', names=['采购单价','采购金额'])
        # df = concat([df1,df2], axis=1)
        df = df1
        df.insert(1,'收货方','大冶华鑫实业有限公司')
        df.insert(9, '单位', '吨')
        df = df[~df.日期.isna()]
        if df.日期.dtype != 'datetime64[ns]':
            df.loc[:,'日期'] = to_timedelta(df.日期, unit='d') + dt(1899,12,30)
            # df.loc[:,'日期'] = df['日期'].apply(dt.date)

        self._tidy_data = df

class minyuan(factory):
    '''
    代表 山东闽源钢铁有限公司
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc_in = {
            "B2": '供货方',
            "F2": '日期',
            None: '车牌号',
        }
        self._oto_loc_out = {
            "B2": '收货方',
            "F2": '日期',
            None: '货物名称',
        }
        self._mtm_loc = {
            '4:11': '行范围',
            'A': '货物名称',
            'C': '车牌号',
            'D': '单位',
            'E': '数量'
        }

    @property
    def tidy_data(self):
        return self._tidy_data

    def get_oto_loc(self, receipt)->dict:
        if(receipt=='入仓单'):
            return self._oto_loc_in
        if(receipt=='出仓单'):
            return self._oto_loc_out
        return None

    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:

        df1 = read_excel(
            datafile, 
            sheet_name=idx, 
            skiprows=3,
            usecols="B:N", 
            names=['日期','车牌号','供货方','货物名称','毛重','皮重','扣重','数量','含税单价','含税金额','备注','单价','现金价'])
        # df2 = read_excel(datafile, 2, skiprows=2, usecols='K:L', names=['采购单价','采购金额'])
        # df = concat([df1,df2], axis=1)
        df = df1
        df.insert(1,'收货方','山东闽源钢铁有限公司')
        df.insert(9, '单位', '吨')
        df = df[~df.日期.isna()]
        if df.日期.dtype != 'datetime64[ns]':
            df.loc[:,'日期'] = to_timedelta(df.日期, unit='d') + dt(1899,12,30)
            # df.loc[:,'日期'] = df['日期'].apply(dt.date)

        self._tidy_data = df

class guigang(factory):
    '''
    代表 首钢贵阳特殊钢有限责任公司
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc_in = {
            "B2": '供货方',
            "F2": '日期',
            None: '车皮号',
        }
        self._oto_loc_out = {
            "B2": '收货方',
            "F2": '日期',
            None: '货物名称',
        }
        self._mtm_loc = {
            '4:11': '行范围',
            'A': '货物名称',
            'C': '车皮号',
            'D': '单位',
            'E': '数量'
        }

    @property
    def tidy_data(self):
        return self._tidy_data


    def get_oto_loc(self, receipt)->dict:
        if(receipt=='入仓单'):
            return self._oto_loc_in
        if(receipt=='出仓单'):
            return self._oto_loc_out
        return None

    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:

        df1 = read_excel(
            datafile, 
            sheet_name=idx, 
            skiprows=1,
            usecols="B:L", 
            dtype={'车皮号':str},
            names=['日期','车皮号','货物名称','毛重','皮重','料净重','扣渣','数量','不含税单价','含税承付金额','应付收购成本'])
        # df2 = read_excel(datafile, 2, skiprows=2, usecols='K:L', names=['采购单价','采购金额'])
        # df = concat([df1,df2], axis=1)
        df = df1
        df.insert(1,'收货方','首钢贵阳特殊钢有限责任公司')
        df.insert(9, '单位', '吨')
        df['供货方'] = None
        df = df[~((df.日期.isna())|(df.日期.str.contains('合计'))|(df.日期.str.contains('日期'))|(df.日期.str.contains('车皮信息')))]
        # df.车皮号 = df.车皮号.astype(str)
        if df.日期.dtype != 'datetime64[ns]':
            df.loc[:,'日期'] = to_timedelta(df.日期, unit='d') + dt(1899,12,30)
            # df.loc[:,'日期'] = df['日期'].apply(dt.date)

        self._tidy_data = df

class taixing(factory):
    '''
    代表 江西台鑫钢铁有限公司
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc_in = {
            "B2": '供货方',
            "F2": '日期',
            None: '车号',
        }
        self._oto_loc_out = {
            "B2": '收货方',
            "F2": '日期',
            None: '货物名称',
        }
        self._mtm_loc = {
            '4:11': '行范围',
            'A': '货物名称',
            'C': '车号',
            'D': '单位',
            'E': '数量'
        }

    @property
    def tidy_data(self):
        return self._tidy_data


    def get_oto_loc(self, receipt)->dict:
        if(receipt=='入仓单'):
            return self._oto_loc_in
        if(receipt=='出仓单'):
            return self._oto_loc_out
        return None

    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:

        df1 = read_excel(
            datafile, 
            sheet_name=idx, 
            # skiprows=1,
            usecols="A:O", 
            names=['日期','车号','毛重','皮重','净重','扣渣','数量','销售单价','含税金额','扣款','销售金额','实际销售金额','下浮','采购金额','供货方'])
        # df2 = read_excel(datafile, 2, skiprows=2, usecols='K:L', names=['采购单价','采购金额'])
        # df = concat([df1,df2], axis=1)
        df = df1
        df.insert(1,'收货方','江西台鑫钢铁有限公司')
        df.insert(2,'货物名称','废钢')
        df.insert(7, '单位', '吨')

        df = df[~(df.日期.isna())]
        # df.车皮号 = df.车皮号.astype(str)
        if df.日期.dtype != 'datetime64[ns]':
            df.loc[:,'日期'] = to_timedelta(df.日期, unit='d') + dt(1899,12,30)
            # df.loc[:,'日期'] = df['日期'].apply(dt.date)

        self._tidy_data = df

class xinjin(factory):
    '''
    代表 河北新金钢铁有限公司
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc_in = {
            "B2": '供货方',
            "F2": '日期',
            None: '车号',
        }
        self._oto_loc_out = {
            "B2": '收货方',
            "F2": '日期',
            None: '货物名称',
        }
        self._mtm_loc = {
            '4:11': '行范围',
            'A': '货物名称',
            'C': '车号',
            'D': '单位',
            'E': '数量'
        }

    @property
    def tidy_data(self):
        return self._tidy_data


    def get_oto_loc(self, receipt)->dict:
        if(receipt=='入仓单'):
            return self._oto_loc_in
        if(receipt=='出仓单'):
            return self._oto_loc_out
        return None

    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:

        df1 = read_excel(
            datafile, 
            sheet_name=idx, 
            skiprows=1,
            )
        df1.rename(columns={'品名':'货物名称','进厂时间':'日期','扣渣净重':'数量'},inplace=True)
        # df2 = read_excel(datafile, 2, skiprows=2, usecols='K:L', names=['采购单价','采购金额'])
        # df = concat([df1,df2], axis=1)
        df = df1
        df.insert(1,'收货方','河北新金钢铁有限公司')
        df.insert(7, '单位', '吨')

        df = df[~(df.日期.isna())]
        # df.车皮号 = df.车皮号.astype(str)
        # if df.日期.dtype != 'datetime64[ns]':
        #     df.loc[:,'日期'] = to_timedelta(df.日期, unit='d') + dt(1899,12,30)
            # df.loc[:,'日期'] = df['日期'].apply(dt.date)

        self._tidy_data = df

class oyelianjin(factory):
    '''
    代表 欧冶链金（湖北）再生资源有限公司
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc_in = {
            "B2": '供货方',
            "F2": '日期',
            None: '车号',
        }
        self._oto_loc_out = {
            "B2": '收货方',
            "F2": '日期',
            None: '货物名称',
        }
        self._mtm_loc = {
            '4:11': '行范围',
            'A': '货物名称',
            'C': '车号',
            'D': '单位',
            'E': '数量'
        }

    @property
    def tidy_data(self):
        return self._tidy_data


    def get_oto_loc(self, receipt)->dict:
        if(receipt=='入仓单'):
            return self._oto_loc_in
        if(receipt=='出仓单'):
            return self._oto_loc_out
        return None

    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:

        df1 = read_excel(
            datafile, 
            sheet_name=idx, 
            skiprows=1,
            )
        df1.rename(columns={'规格型号':'货物名称','月份':'日期','结算数量':'数量','收款人':'供货方'},inplace=True)
        # df2 = read_excel(datafile, 2, skiprows=2, usecols='K:L', names=['采购单价','采购金额'])
        # df = concat([df1,df2], axis=1)
        df = df1
        df.insert(1,'收货方','欧冶链金（湖北）再生资源有限公司')
        df.insert(7, '单位', '吨')
        df['车号'] = ""

        df = df[~(df.日期.isna())]
        # df.车皮号 = df.车皮号.astype(str)
        # if df.日期.dtype != 'datetime64[ns]':
        #     df.loc[:,'日期'] = to_timedelta(df.日期, unit='d') + dt(1899,12,30)
            # df.loc[:,'日期'] = df['日期'].apply(dt.date)

        self._tidy_data = df

class corpself(factory):
    '''
    代表 企业自身
    '''
    def __init__(self)->None:
        self._tidy_data = None
        self._oto_loc = {
            'M2':'填单日期',
            'E3':'收款单位', 'M3':'请款部门',
            'E4':'银行账号', 'M4':'开户银行',
            'F5':'金额（大写）',
            'M5':'转款金额', 
            'B7':'用途', 
            'O9':'单据数量'
        }
        self._mtm_loc = None    

    @property
    def tidy_data(self):
        return self._tidy_data

    def get_oto_loc(self, receipt)->dict:
        if(receipt=='请款单'):
            return self._oto_loc        
        return None
    
    @property
    def mtm_loc(self):
        return self._mtm_loc

    def read_data(self, datafile: str, idx)->None:
        df = read_excel(datafile, sheet_name=idx,dtype={'行号':str})

        df['金额（大写）'] = df.转款金额.apply(amount_converter)

        self._tidy_data = df
    